package com.holyn.guofang.presenter;


import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Holyn on 2017/6/29.
 */

public class PresenterManager<T> {
    public AbstractBasePresenterImp abstractBasePresenterImp;
    private final int requestAction;

    public PresenterManager(final int requestAction, AbstractBasePresenterImp abstractBasePresenterImp) {
        this.requestAction = requestAction;
        this.abstractBasePresenterImp = abstractBasePresenterImp;
    }

    public interface OnResponseListener<K> {
        void responseSuccess(int requestAction, K t);
    }

    public void subscribe(Observable<T> observable, OnResponseListener<T> onResponseListener) {
        abstractBasePresenterImp.requestStart(requestAction);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<T>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        abstractBasePresenterImp.addDisposable(requestAction, d);
                    }

                    @Override
                    public void onNext(@NonNull T t) {
                        onResponseListener.responseSuccess(requestAction, t);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        abstractBasePresenterImp.requestError(requestAction, e);
                    }

                    @Override
                    public void onComplete() {
                        abstractBasePresenterImp.requestComplete(requestAction);
                    }
                });
    }
}
